package com.test;

import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Random;

public class GenerateURL {
    public static void main(String[] args) {
        long capacity = 2*1024L;//2G
        generate(capacity); //2G数据，测试generate finish,耗时：58秒

//        generateSpecicalData();
    }

    public static void generateSpecicalData(){
        File file = new File("urls1.txt");//文件位置
        try(BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file))) {
            for(int i = 1; i < 200; i++){
                String url = genrerateRandomURL() + "\r\n";
                for(int j = 0; j < i; j++){
                    bos.write(url.getBytes());
                }

            }
        }catch (Exception e){
            throw new RuntimeException("generate url err", e);
        }

    }

    public static void generate(long capacity){
        long beginTime = System.currentTimeMillis();
        File file = new File("urls.txt");//文件位置
        try(BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file))) {
            long size = 0;
            System.out.println("generate now...");
            while (size < capacity) {
                String url = genrerateRandomURL() + "\r\n";
                byte[] bytes = url.getBytes();
                size += bytes.length;
                bos.write(bytes);
            }
        }catch (Exception e){
            throw new RuntimeException("generate url err", e);
        }
        long endTime = System.currentTimeMillis();

        System.out.println("generate finish,耗时：" + ((endTime-beginTime)/1000) + "秒");
    }

    public static String genrerateRandomURL(){
        Random random = new Random();
        int length = random.nextInt(6)+3;  //长度为3到8
       StringBuffer sb = new StringBuffer();
        sb.append("http://").append(randomAlphaNumber(length))
                .append(".").append("baidu")
                .append(".com");
        return sb.toString();
    }

    public static String randomAlphaNumber(int length){
        StringBuffer sb = new StringBuffer();
        String s = "abcdefghijklmnopqrstuvwxyz1234567890";
        char[] c = s.toCharArray();
        Random random = new Random();
        for( int i = 0; i < length; i ++) {
            sb.append(c[random.nextInt(c.length)]);
        }
        return sb.toString();
    }
}
